# -*- conding:UTF-8 -*-

'''
@ Project: P8_02_LumenIM-flask
@ File: group_app.py
@ Author: 罗婷
@ Date：2022/7/11 16:16

'''
import redis
from flask import Blueprint, jsonify, g
from flask_restful import Api, Resource, reqparse, marshal
from qiniu import Auth

from common.model_fields.user_fs import user_fieklds, group_fields
from common.models import db
from common.models.users import Users, Group, GroupMember, User_Group
from common.utils.login_auth import login_requir

group_bp = Blueprint('group_bp', __name__, url_prefix='/api/v1/group')
api = Api(group_bp)

# 获取用户可邀请加入群组的好友列表
class FriendList(Resource):
    @login_requir
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('group_id')
        args = parser.parse_args()
        group_id = args['group_id']
        print('获取用户可邀请加入群组的好友列表!!!!~~~~~~接收到的group_id', group_id)
        uid = g.uid
        rds = redis.Redis(db=10)
        key = f'{uid}_fs'
        res = rds.smembers(key)
        if not res:
            return jsonify(message='还未有好友', code=200, data='')
        f_list_id = [i.decode() for i in res]
        friend_list = []
        for i in f_list_id:
            user = Users.query.filter_by(id=i).first()
            user_data = marshal(user, user_fieklds)
            friend_list.append(user_data)
        return jsonify(message='ok', code=200, data=friend_list)


# 好友邀请提交
class ServeFriend(Resource):
    def post(self):
        #         group_id: parseInt(this.from.groupId),
        #         ids: this.getIds().join(','),
        parser = reqparse.RequestParser()
        parser.add_argument('group_id')
        parser.add_argument('ids')
        args = parser.parse_args()
        group_id = args['group_id']
        ids = args['ids']
        print('好友邀请提交  group_id', group_id, 'ids', ids)
        ...
        return 'jjj'

# 创建聊天群
class CreateGroup(Resource):
    @login_requir
    def post(self):
        ...
        parser = reqparse.RequestParser()
        parser.add_argument('avatar')
        parser.add_argument('ids')
        parser.add_argument('name')
        parser.add_argument('profile')
        args = parser.parse_args()
        avatar = args['avatar']    # 群头像
        ids = args['ids']          # 群成员的 用户id     '2,5'
        names = args['name']       # 群名称
        profile = args['profile']  # 群介绍
        print('创建聊天群  avatar', avatar, 'ids', ids, 'name', names, 'profile', profile)
        ids = ids.split(',')       # '2,5'  ['2', '5']
        ids.append(g.uid)
        print('所有的群成员 用户id', ids)
        # 群成员表添加数据
        group_members_list = []
        for i in ids:
            i = int(i)
            #　创建群成员
            try:
                group_member = GroupMember(user_id=i)
                db.session.add(group_member)
                db.session.commit()
                group_members_list.append(group_member)
            except Exception as e:
                print(f'群成员添加失败{e}')
                return jsonify(message="创建群成员失败", code=500)

        try:
            group = Group(creator_id=g.uid, group_name=names, profile=profile, avatar=avatar, member=group_members_list)
            db.session.add(group)
            db.session.commit()
        except Exception as e:
            print(f'创建群失败{e}')
            return jsonify(message="创建群失败", code=500)

        return jsonify(message="创建群成功", code=200)


# 展示群
class GroupList(Resource):
    @login_requir
    def get(self):
        member = GroupMember.query.filter_by(user_id=g.uid).first()
        groups = member.member_group
        group_list = []
        for i in groups:
            data = marshal(i, group_fields)
            group_list.append(data)
        return jsonify(message='ok', code=200, data=group_list)


# 获取用户可邀请加入群组的好友列表
api.add_resource(FriendList, '/member/invites')
# 创建聊天群
api.add_resource(CreateGroup, '/create')
# 邀请好友加入群聊服务接口
api.add_resource(ServeFriend, '/invite')
# 展示群
api.add_resource(GroupList, '/list')
